#!/usr/bin/perl -w
#the cut video file;
use DBI;
use mydb;
use File::Path;
use myvideo;
use Digest::MD5;
use server;
use myserver;
use Net::SCP::Expect;
use File::Basename qw<basename dirname>;
 

my_connect();
$sql = "SELECT * FROM t_task WHERE status = 'prepare'";

#when file is upload down fetch row from t_task

$sth = $dbconn->prepare($sql) or die $dbconn->errstr;

$sth->execute() or die "错误: " . $sth->errstr;

  while (@data0 = $sth->fetchrow()) {

  $rowid = $data0[0];
  $file = $data0[5];
  $playtime = $data[20];
  $ip =  get_ServerIP($servername);
  $spath = get_ServerPath($servername);

  $spath = $spath."/$rowid";

  rmtree($spath)||die "删除目录错误 $!";
  mkdir($spath, 0777)||die"不能创建$spath目录";

  @userpasswd = get_ServerUserPasswd(@servername);
  $user = $userpasswd[0];
  $passwd = $userpasswd[1];
  #print "rowid:", $rowid, "file:", $file, "playtime:", $playtime, "ip:", $ip, "user:", $user, "passwd:", $passwd, "spath:", $spath, "\n";

  $s_server=$data0[6];
  $s_ip = get_ServerIP($s_server);
  @userpasswd1 = get_ServerUserPasswd($s_server);
  $s_user = $userpasswd1[0];
  $s_passwd = $userpasswd1[1];
#把文件从原服务器的位置拷贝到预处理服务器中.

  my $scpe = Net::SCP::Expect->new(user=>"$s_user",password=>"$s_passwd", auto_yes=>1);

  $scpe->scp("$s_ip:$file", "$spath");
#对于传输的文件进行分割，首先判断是否需要分割，并把分割的结果写入到分割的任务表中。

  $filename = basename $file;
  $filename = "$spath\/$filename";
  $res = `mkvmerge --split 300s $filename -o $filename.%05d`; 
  $res1 = `ls $filename.?????|wc -l`;

  for($i = 1; $i <= $res1; $i++) {
#分割后的内容写入到t_prepare

      $sql = "insert into t_prepare(tid, spath, level, ctime, vcode, acode, playtime, logo, x, y, total, cur, server, cpath, status, scomment) values($rowid, \'$filename\', 5, now(), ?, ?, 300, '', 0, 0, $res1, ?, \'$servername\', ?, 'cut', '')"; 

      $stmp1 = "0000".$i;
      $stmp1 = substr($stmp1, length($stmp1)-5, 5);
      $pth = $dbconn->prepare($sql) or die $dbconn->errstr;
      $pth->execute('', '', $i,  $filename."\.".$stmp1);
  }

#在分割后把任务内容填加进c_control表中。
  $sql = "insert into c_control(tid, level, total, ctime, etime) values($rowid, 5, $res1, now(), now())";
  $pth = $dbconn->prepare($sql) or die $dbconn->errstr;
  $pth->execute();

#
}

my_disconnect();
